package com.example.redistest.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("chaomai")
public class RedisChaoMai {


    private static final Logger logger = LoggerFactory.getLogger(RedissonLockController.class);

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 为了防止超卖，可以加锁，单机jvm没什么问题，但是分布式下(比如用nginx分发的话) 还是有问题
     */
    @RequestMapping("/testlock")
    public String deductStock() throws InterruptedException {
        synchronized (this) {
            int stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("stock")); //获取库存
            if (stock > 0) {
                int realStock = stock - 1;  //库存减1
                stringRedisTemplate.opsForValue().set("stock", realStock + "");//设置最新库存
                System.out.println("扣减成功，剩余库存:" + realStock + "");
            } else {
                System.out.println("扣减失败，库存不足");
            }
        }
        return "结束";
    }
}
